package org.management.system.service.impl;

import java.util.Arrays;
import java.util.List;
import org.management.base.BaseServiceImpl;
import org.management.system.dao.RoleDao;
import org.management.system.dao.RoleResourceDao;
import org.management.system.entity.RoleEntity;
import org.management.system.entity.RoleResourceEntity;
import org.management.system.service.RoleService;
import org.management.utils.DateUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import javax.annotation.Resource;

/**
 * 功能描述
 * 角色服务类
 * @author jiangyan
 * @date 2019/03/14
 * @description
 * @project management
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleEntity> implements RoleService {
	
	@Resource
	private RoleDao roleDao;
	
	@Resource
	private RoleResourceDao roleResourceDao;
	/**
	 * 根据用户id获取角色集
	 */
	@Override
	public List<RoleEntity> getRoleByUserId(String userId) {
		return roleDao.getRoleByUserId(userId);
	}
	/**
	 * 根据用户id获取角色id集
	 */
	@Override
	public String getRoleIdsByUserId(String userId) {
		return roleDao.getRoleIdsByUserId(userId);
	}
	/**
	 * 根据资源id获取角色集合
	 */
	@Override
	public List<RoleEntity> getRolesByResourceId(String resourceId) {
		return roleDao.getRolesByResourceId(resourceId);
	}
	/**
	 * 根据资源id获取角色ids字符串
	 */
	@Override
	public String getRoleIdsByResourceId(String resourceId) {
		return roleDao.getRoleIdsByResourceId(resourceId);
	}
	@Override
	public void saveRoleRelation(String resourceId, String[] roleArray) {
		Example example = new Example(RoleResourceEntity.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("resourceId",resourceId);
		criteria.andNotIn("roleId", Arrays.asList(roleArray));
		this.roleResourceDao.deleteByExample(example);
		for(String roleId : roleArray) {
			RoleResourceEntity entity = new RoleResourceEntity();
			entity.setRoleId(roleId);
			entity.setResourceId(resourceId);
			RoleResourceEntity roleResourceEntity = this.roleResourceDao.selectOne(entity);
			if(roleResourceEntity == null) {
				entity.setCreateTime(DateUtils.getCurDateTime());
//				entity.setCreateUser(TokenManager.getUserId());
				this.roleResourceDao.insertSelective(entity);
			}
		}
		
	}
	
}
